package com.bxait.toymail.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.bxait.com.constant.ProductConstant;
import com.bxait.com.to.SkuReductionTo;
import com.bxait.com.to.SpuBoundTo;
import com.bxait.com.to.es.SkuEsModel;
import com.bxait.com.utils.PageUtils;
import com.bxait.com.utils.Query;
import com.bxait.com.utils.R;
import com.bxait.com.vo.product.*;
import com.bxait.toymail.product.entity.*;
import com.bxait.toymail.product.feign.CouponFeignService;
import com.bxait.toymail.product.feign.SearchFeignService;
import com.bxait.toymail.product.feign.WareFeignService;
import com.bxait.toymail.product.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bxait.toymail.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    @Qualifier("spuImagesService")
    private SpuImagesService imagesService;

    @Resource
    @Qualifier("skuInfoService")
    private SkuInfoService skuInfoService;

    @Resource
    @Qualifier("brandService")
    private BrandService brandService;

    @Resource
    @Qualifier("categoryService")
    private CategoryService categoryService;

    @Resource
    @Qualifier("spuInfoDescService")
    private SpuInfoDescService spuInfoDescService;


    @Resource
    @Qualifier("skuImagesService")
    private SkuImagesService skuImagesService;

    @Resource
    @Qualifier("skuSaleAttrValueService")
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    @Qualifier("productAttrValueService")
    ProductAttrValueService attrValueService;

    @Resource
    @Qualifier("attrService")
    AttrService attrService;


    @Resource
    private CouponFeignService couponFeignService;

    @Resource
    private SearchFeignService searchFeignService;

    @Resource
    WareFeignService wareFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * @param params
     * @==============History===============<br/>
     * @Description // TODO  获取商品的spu列表
     * @Date 2023/3/20 21:09
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return com.bxait.com.utils.PageUtils
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }
        // 品牌id的条件
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        // 分类id的条件
        String cateLogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(cateLogId) && !"0".equals(cateLogId)){
            queryWrapper.eq("catalog_id",cateLogId);
        }
        // 最小价格的条件
        String min = (String) params.get("min");
        if(!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",min);
        }

        String max = (String) params.get("max");
        if(!StringUtils.isEmpty(max)  ){
            try{
                BigDecimal bigDecimal = new BigDecimal(max);
                if(bigDecimal.compareTo(new BigDecimal("0"))==1){
                    queryWrapper.le("price",max);
                }
            }catch (Exception e){
            }
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * @param vo
     * @==============History===============<br/>
     * @Description // TODO  保存商品spu信息
     * @Date 2023/3/20 21:34
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return void
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1.保存spu的基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        // 设置创建时间与修改时间
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setCreateTime(new Date());
        this.save(spuInfoEntity);
        // 2.保存spu的描述信息
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        String join = String.join(",", decript);
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(join);
        spuInfoDescService.save(spuInfoDescEntity);

        // 3.保存spu的图片集 pms_spu_images
        imagesService.saveImages(spuInfoEntity.getId(),vo.getImages());

        // 4.保存spu积分信息
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());

         R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }

        // 保存spu的规格属性信息
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            AttrEntity id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        // 5.保存当前spu的sku信息
        List<Skus> skus = vo.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach(item->{
               // 5.1 保存sku基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                // 找到图片中的默认图片
                for (Images image : item.getImages()) {
                    if(image.getDefaultImg() == 1){
                        skuInfoEntity.setSkuDefaultImg(image.getImgUrl());
                    }
                }

                // 设置品牌的id
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());

                // 设置销量
                skuInfoEntity.setSaleCount(0L);

                // 设置spu的id
                skuInfoEntity.setSpuId(spuInfoEntity.getId());

                // 设置分类的id
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());

                // 保存sku基本信息
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                // 5.2保存sku的图片信息
                List<Images> images = item.getImages();
                List<SkuImagesEntity> skuImages = images.stream()
                        .filter(img -> !StringUtils.isEmpty(img.getImgUrl()))
                        .map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgSort(0);
                    return skuImagesEntity;
                }).collect(Collectors.toList());

                skuImagesService.saveBatch(skuImages);

                // 5.3保存sku的销售属性
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setAttrSort(0);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);


                // 5.4保存sku的优惠卷信息sms_sku_ladder/sms_sku_full_reduction/sms_member_price

                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                // 打折的件数是需要大于0的,打折的金额是需要大于0的
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }

                }



            });
        }

    }

    /*
     * @param spuId
     * @==============History===============<br/>
     * @Description // TODO  上架商品到es中
     * @Date 2023/4/13 22:19
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return void
     */
    @Override
    public void up(Long spuId) {
        // 1.查询出当前spu商品的sku信息,品牌,分类的信息
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        // 1.1收集当前skus的id
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // 2.查询当前spu信息的所有可以被检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        // 2.2获取可以被检索的规格属性
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        // 2.3收集属性信息
        List<Attr> attrLists = baseAttrs.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    Attr attr = new Attr();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                })
                .collect(Collectors.toList());

        // 3.发送远程请求,获取商品sku的库存信息
        // 3.1map中key是当前商品的skuId,values是当前商品是否有货
        Map<Long, Boolean> stockMap = null;
        try{
            R r = wareFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = r.getData("data",typeReference)
                        .stream()
                        .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常:原因{}",e);
        }

        // 4.封装每个sku的信息到SkuEsModel模型中
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProductsToEsModel = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            // 4.1拷贝基础数据
            BeanUtils.copyProperties(sku,skuEsModel);

            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            // 4.2设置库存信息
            if(finalStockMap == null) {
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            // 4.3设置热度评分
            skuEsModel.setHotScore(0L);
            // 4.4设置品牌信息,分类信息
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setCatalogName(categoryEntity.getName());


            // 4.5设置检索属性信息
            skuEsModel.setAttrs(attrLists);
            return skuEsModel;
        }).collect(Collectors.toList());


        // 5.将数据发送到es中保存,发送远程请求到search服务
        R r = searchFeignService.productStatusUp(upProductsToEsModel);
        if(r.getCode() == 0){
            // 商品上架成功
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            // 商品上架失败,触发重试机制
            //Feign调用流程
            /*
             * 1、构造请求数据，将对象转为json；
             *      RequestTemplate template = buildTemplateFromArgs.create(argv);
             * 2、发送请求进行执行（执行成功会解码响应数据）：
             *      executeAndDecode(template);
             * 3、执行请求会有重试机制
             *      while(true){
             *          try{
             *            executeAndDecode(template);
             *          }catch(){
             *              try{try.continueOrPropagate(e)}catch(){throw ex;}
             *              continue;
             *          }
             *
             *      }
             */
        }

    }

    /*
     * @param skuId
     * @==============History===============<br/>
     * @Description //   根据skuId获取spu信息
     * @Date 2023/5/13 2023/5/13 
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return SpuInfoEntity
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = this.getById(spuId);
        return spuInfoEntity;
    }

}